package service

import (
	"duoke/model"
	"duoke/tables"
	"duoke/utils/api345"
	"duoke/utils/gconv"
	"duoke/utils/orm"
	"duoke/utils/storage"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
)

var HomeVideo = new(homeVideoService)

type homeVideoService struct{}

func (s *homeVideoService) List(c *gin.Context, req *model.ReqList) (*[]tables.HomeVideo, int64, error) {
	user, err := Request.Account(c)
	if err != nil {
		return nil, 0, err
	}
	where := fmt.Sprintf("acid=%d", user.Id)
	var m []tables.HomeVideo
	count, err := tableCommon.QueryListWithPageV2(where, req.PageNo, req.PageSize).OrderBy("id desc").
		FindAndCount(&m)
	if err != nil {
		return nil, 0, err
	}
	return &m, count, nil
}
func (s *homeVideoService) Save(c *gin.Context, req *tables.HomeVideo) error {
	user, err := Request.Account(c)
	if err != nil {
		return err
	}
	// menu_id是否存在
	get, err := orm.Db.Where("id=?", req.MenuId).Get(&tables.HomeMenu{})
	if err != nil {
		return err
	}
	if !get {
		return errors.New("值错误【menu_id】")
	}
	req.Acid = user.Id
	if req.Gather != "" {
		jiexi, err := api345.NewConfig().Jiexi(req.Gather)
		if err != nil {
			return err
		}
		if jiexi.Data.Url == "" {
			return errors.New("解析失败【url参数缺失】")
		}
		setting, err := Upload.Setting(c)
		urlv2, err := storage.Qiniu.UploadByURLV2(jiexi.Data.Url, &storage.FormUploader{
			Suffix:  ".png",
			Acid:    user.Id,
			Setting: setting,
		})
		urlv2.GroupId = gconv.Int(0)
		err = Upload.Save(c, *urlv2)
		if err != nil {
			return err
		}
		req.Url = urlv2.Url
	}
	if req.Id == 0 {
		_, err = orm.Db.Insert(req)
		if err != nil {
			return err
		}
	} else {
		_, err = orm.Db.Where("id=?", req.Id).Update(req)
		return err
	}
	return nil
}
func (s *homeVideoService) Del(c *gin.Context, req *model.ReqId) error {
	user, err := Request.Account(c)
	if err != nil {
		return err
	}
	_, err = orm.Db.ID(req.Id).Where("acid=?", user.Id).Delete(&tables.HomeVideo{})
	return err
}
func (s *homeVideoService) Info(c *gin.Context, where string, field string) (*tables.HomeVideo, error) {
	user, err := Request.User(c)
	if err != nil {
		return nil, err
	}
	where = fmt.Sprintf("%s and acid=%d", where, user.Acid)
	var m tables.HomeVideo
	get, err := orm.Db.Where(where).Cols(field).Get(&m)
	if err != nil {
		return nil, err
	}
	if !get {
		return nil, errors.New("获取数据不存在")
	}
	return &m, err
}
func (s *homeVideoService) Infos(c *gin.Context, where string, field string) (*[]tables.HomeVideo, error) {
	user, err := Request.User(c)
	if err != nil {
		return nil, err
	}
	where = fmt.Sprintf("%s and acid=%d", where, user.Acid)
	var m []tables.HomeVideo
	get, err := orm.Db.Where(where).Cols(field).Get(&m)
	if err != nil {
		return nil, err
	}
	if !get {
		return nil, errors.New("获取数据不存在")
	}
	return &m, err
}
